package Concurrent.Lock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author chenjunjie
 * @since 2018-08-17
 */
public class CASdemo {
    private AtomicInteger atomicI = new AtomicInteger(0);
    private int i = 0;

    public static void main(String[] args) {
        final CASdemo cas = new CASdemo();
        List<Thread>  ts = new ArrayList<Thread>(600);
        long start = System.currentTimeMillis();
        for (int k=0; k<10; k++) {
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    cas.count();
                    cas.safeCount();
                }
            });
            ts.add(t);
        }

        for (Thread t : ts){
            t.start();
        }

        // 等待所有线程执行完成
        for (Thread t : ts){
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void count(){
        i++;
    }

    public void safeCount(){
        while(true){
            int j = atomicI.get();
            boolean suc = atomicI.compareAndSet(j, ++j);
            if(suc) {
                break;
            }
        }
    }
}
